package com.management.department.teacherinfosystem.Controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.management.department.teacherinfosystem.Entity.TalentHonor;
import com.management.department.teacherinfosystem.Entity.User;
import com.management.department.teacherinfosystem.Repository.TalentHonorRepository;
import com.management.department.teacherinfosystem.Repository.UserRepository;

@RestController
@RequestMapping("/api/honors")
@CrossOrigin(origins = "*")
public class TalentHonorController {

	@Autowired
	private TalentHonorRepository honorRepository;
	@Autowired
	private UserRepository userRepository;

	private Date parseDate(Object value) {
		if (value == null) return null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.parse(String.valueOf(value));
		} catch (Exception e) {
			return null;
		}
	}

	@PostMapping
	@Transactional
	public ResponseEntity<?> create(@RequestBody Map<String, Object> payload) {
		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth.getName();
		User currentUser = userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
		if (currentUser == null) return ResponseEntity.status(401).body("用户未登录");

		TalentHonor h = new TalentHonor();
		h.setUserId(currentUser.getId());
		h.setCategory((String) payload.getOrDefault("category", null));
		h.setTitleFullName((String) payload.getOrDefault("title_full_name", null));
		h.setGrantingOrganization((String) payload.getOrDefault("granting_organization", null));
		h.setSelectionDate(parseDate(payload.get("selection_date")));
		h.setValidFrom(parseDate(payload.get("valid_from")));
		h.setValidTo(parseDate(payload.get("valid_to")));
		Object p = payload.get("is_permanent");
		h.setIsPermanent(p == null ? Boolean.FALSE : Boolean.valueOf(String.valueOf(p)));
		h.setNotes((String) payload.getOrDefault("notes", null));
		h.setCreatedAt(new Date());
		h.setUpdatedAt(new Date());

		TalentHonor saved = honorRepository.save(h);
		return ResponseEntity.ok(Map.of("id", saved.getId()));
	}

	@GetMapping("/mine")
	@Transactional(readOnly = true)
	public ResponseEntity<?> mine() {
		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth.getName();
		User currentUser = userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
		if (currentUser == null) return ResponseEntity.status(401).body("用户未登录");
		return ResponseEntity.ok(honorRepository.findByUserId(currentUser.getId()));
	}

	@GetMapping("/all")
	@Transactional(readOnly = true)
	public ResponseEntity<?> all() {
		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth.getName();
		User currentUser = userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
		if (currentUser == null) return ResponseEntity.status(401).body("用户未登录");
		boolean isAdmin = currentUser.getUserRoles().stream()
				.anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
		if (!isAdmin) return ResponseEntity.status(403).body("权限不足");

		List<TalentHonor> list;
		try {
			list = honorRepository.findAllOrdered();
		} catch (Exception ignore) {
			list = honorRepository.findAll();
		}

		List<Map<String, Object>> result = new ArrayList<>();
		for (TalentHonor h : list) {
			Map<String, Object> m = new HashMap<>();
			m.put("id", h.getId());
			m.put("category", h.getCategory());
			m.put("titleFullName", h.getTitleFullName());
			m.put("grantingOrganization", h.getGrantingOrganization());
			m.put("selectionDate", h.getSelectionDate());
			m.put("validFrom", h.getValidFrom());
			m.put("validTo", h.getValidTo());
			m.put("isPermanent", h.getIsPermanent());
			m.put("notes", h.getNotes());
			m.put("createdAt", h.getCreatedAt());
			m.put("updatedAt", h.getUpdatedAt());
			if (h.getUserId() != null) {
				userRepository.findById(h.getUserId()).ifPresent(u -> m.put("userName", u.getName()));
			}
			result.add(m);
		}
		return ResponseEntity.ok(result);
	}

	@GetMapping("/{id:[0-9]+}")
	public ResponseEntity<?> get(@PathVariable("id") Long id) {
		TalentHonor h = honorRepository.findById(id).orElse(null);
		if (h == null) return ResponseEntity.notFound().build();
		Map<String, Object> m = new HashMap<>();
		m.put("honor", h);
		if (h.getUserId() != null) {
			userRepository.findById(h.getUserId()).ifPresent(u -> {
				m.put("userName", u.getName());
				m.put("department", u.getDepartment());
			});
		}
		return ResponseEntity.ok(m);
	}

	@PutMapping("/{id:[0-9]+}")
	public ResponseEntity<?> update(@PathVariable("id") Long id, @RequestBody Map<String, Object> payload) {
		TalentHonor h = honorRepository.findById(id).orElse(null);
		if (h == null) return ResponseEntity.notFound().build();

		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth.getName();
		User currentUser = userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
		if (currentUser == null) return ResponseEntity.status(401).body("用户未登录");
		boolean isAdmin = currentUser.getUserRoles().stream()
				.anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
		if (!Objects.equals(h.getUserId(), currentUser.getId()) && !isAdmin) {
			return ResponseEntity.status(403).body("无权修改");
		}

		h.setCategory((String) payload.getOrDefault("category", h.getCategory()));
		h.setTitleFullName((String) payload.getOrDefault("title_full_name", h.getTitleFullName()));
		h.setGrantingOrganization((String) payload.getOrDefault("granting_organization", h.getGrantingOrganization()));
		Date sd = parseDate(payload.get("selection_date"));
		if (sd != null) h.setSelectionDate(sd);
		Date vf = parseDate(payload.get("valid_from"));
		if (vf != null) h.setValidFrom(vf);
		Date vt = parseDate(payload.get("valid_to"));
		if (vt != null) h.setValidTo(vt);
		Object p = payload.get("is_permanent");
		if (p != null) h.setIsPermanent(Boolean.valueOf(String.valueOf(p)));
		h.setNotes((String) payload.getOrDefault("notes", h.getNotes()));
		h.setUpdatedAt(new Date());

		honorRepository.save(h);
		return ResponseEntity.ok("OK");
	}

	@DeleteMapping("/{id:[0-9]+}")
	public ResponseEntity<?> delete(@PathVariable("id") Long id) {
		TalentHonor h = honorRepository.findById(id).orElse(null);
		if (h == null) return ResponseEntity.notFound().build();
		org.springframework.security.core.Authentication auth =
				org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication();
		String currentUsername = auth.getName();
		User currentUser = userRepository.findByUsernameWithRoles(currentUsername).orElse(null);
		if (currentUser == null) return ResponseEntity.status(401).body("用户未登录");
		boolean isAdmin = currentUser.getUserRoles().stream()
				.anyMatch(ur -> ur.getRole() != null && "admin".equalsIgnoreCase(ur.getRole().getName()));
		if (!Objects.equals(h.getUserId(), currentUser.getId()) && !isAdmin) {
			return ResponseEntity.status(403).body("无权删除");
		}
		honorRepository.deleteById(id);
		return ResponseEntity.ok().build();
	}
} 